package juf.adapter;


import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

import juf.Property;

/**Binding between a JTree component and a Property data source 
 * 
 * This is a read-only control.
 * 
 * @author Dale Halliwell
 */

@SuppressWarnings("serial")
public class JTreeAdapter extends AbstractAdapter implements Adapter {

	private JTree treecomponent; //so can be accessed by getDataComponent()

	/**Create a new JTreeAdapter bound to a property
	 * @param property the Property to bind to
	 */
	public JTreeAdapter(Property property) { 
		if (property.getValue() instanceof Object[]){
			DefaultMutableTreeNode root = processHierarchy((Object[]) property.getValue());
			this.treecomponent = new JTree(root);			
			this.component = new JScrollPane(treecomponent);
			treecomponent.setPreferredSize(new Dimension(300,100));
			component.setPreferredSize(new Dimension(300,100));
			bind(property, new Dimension(350,100));
		}
		else
			throw new IllegalArgumentException("JTreeAdapter can not be bound to members with types other than Object[]");
		
		//TODO handle double-click of objects in the tree
		
	}
	
	
	  /** Small routine that will make node out of the first entry
	   *  in the array, then make nodes out of subsequent entries
	   *  and make them child nodes of the first one. The process is
	   *  repeated recursively for entries that are arrays.
	   */	    
	  private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
	    DefaultMutableTreeNode node =   new DefaultMutableTreeNode(hierarchy[0]);
	    DefaultMutableTreeNode child;
	    for(int i=1; i<hierarchy.length; i++) {
	    	Object nodeSpecifier = hierarchy[i];
	    	if (nodeSpecifier instanceof Object[])  // Ie node with children
	    		child = processHierarchy((Object[]) nodeSpecifier);
	    	else
	    		child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
	    	node.add(child);
	    }
	    return(node);
	  }

	
	/* (non-Javadoc)
	 * @see adapters.Adapter#refresh()
	 */
	@Override
	public void refresh() {
		//JTreeAdapter is immutable atm
	}

	/* (non-Javadoc)
	 * @see adapters.Adapter#save()
	 */
	@Override
	public void save() {
		//JTreeAdapter is immutable atm
	}
	
	
	@Override
	public Component getDataComponent(){
		return treecomponent;
	}

}
